package se.thoka.twt.client.utils;

/**
 * @author Thobias Karlsson, Thoka
 * @since 8 jan 2010
 */
public class ParseUtil {

	/**
	 * @param intStr The integer string to parse
	 * @param defaultValue The default value to return if parsing fails
	 * @return parsed int
	 */
	public static int tryParse(String intStr, int defaultValue) {
		int result;
		try {
			result = Integer.parseInt(StringUtils.trim(intStr));
		} catch (Exception e) {
			result = defaultValue;
		}

		return result;
	}
	/**
	 * @param longStr The long string to parse
	 * @param defaultValue The default value to return if parsing fails
	 * @return parsed long
	 */
	public static long tryParse(String longStr, long defaultValue) {
		long result;
		try {
			result = Long.parseLong(StringUtils.trim(longStr));
		} catch (Exception e) {
			result = defaultValue;
		}

		return result;
	}

	/**
	 * @param pxStr A string containing pixels, e.g. "13px"
	 * @param defaultValue The default value to return if parsing fails
	 * @return The parsed pixels
	 */
	public static int tryParsePx(String pxStr, int defaultValue) {
		int result;
		try {
			result = tryParse(pxStr.substring(0, pxStr.length() - 2), defaultValue);
		} catch (Exception e) {
			TWTLogger.log("Unable to parse px str \"" + pxStr + "\"", e);
			result = defaultValue;
		}

		return result;
	}
}
